<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>
        <template #right>
          <el-button v-allow="'export'" type="warning" size="small" @click="$router.push('/employees/import')">excel导入</el-button>
          <el-button v-allow="'import'" type="danger" size="small" @click="hExport">excel导出</el-button>
          <el-button type="primary" size="small" @click="showDialog=true">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table
          border
          :data="list"
          :default-sort="{prop: 'workNumber'}"
        >
          <el-table-column label="序号" type="index" :index="indexMethod" />
          <el-table-column label="头像">
            <template slot-scope="scope">
              <image-holder :src="scope.row.staffPhoto" />
            </template>
          </el-table-column>
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="工号" sortable prop="workNumber" />
          <el-table-column label="聘用形式">
            <template slot-scope="scope">
              类型：{{ formatEmployment(scope.row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" sortable prop="timeOfEntry" />
          <el-table-column label="操作" width="280">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="$router.push('/employees/detail?id='+scope.row.id)">查看</el-button>
              <el-button v-allow="'allotUser'" type="text" size="small" @click="hAssignRole(scope.row)">分配角色</el-button>
              <el-button v-allow="'delete'" type="text" size="small" @click="del(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <div style="height: 60px; margin-top: 10px;text-align: center;">
          <!-- 分页 -->
          <el-pagination
            background
            layout="total, sizes,prev, pager, next, jumper"
            :total="total"
            :page-size="pageParams.size"
            :current-page="pageParams.page"
            :page-sizes="[3,5,10]"
            @current-change="hCurrentChange"
            @size-change="hSizeChange"
          />
        </div>
      </el-card>
    </div>
    <!-- 新增员工弹窗 -->
    <el-dialog
      title="添加"
      :visible.sync="showDialog"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <dalog v-if="showDialog" @close="Dclose" @update-empolyee="hUpdateEmpolyee" />
    </el-dialog>

    <!-- 分配权限弹窗 -->
    <el-dialog
      title="分配角色"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="showDialogRole"
    >
      <assign-role v-if="showDialogRole" :employee-id="curEmployeId" @close="showDialogRole=false" />
    </el-dialog>
  </div>
</template>

<script>
// 引入组件
import AssignRole from './assignRole'
// 引入头像组件
import imageHolder from '@/components/img-hodel/index.vue'
import Dalog from './dalog.vue'
import { getEmployeeList, delEmployee } from '@/api/employees'
import EmployeeEnum from '@/constant/employees'
const hireType = EmployeeEnum.hireType.reduce((acc, item) => { return { ...acc, [item.id]: item.value } }, {})
export default {
  name: '',
  components: { Dalog, imageHolder, AssignRole },
  props: {},
  data() {
    return {
      curEmployeId: '', // 当前的员工编号
      roleIds: [], // 保存当前选中的权限列表
      showDialogRole: false,
      showDialog: false,
      list: [],
      total: 0,
      pageParams: {
        page: 1,
        size: 5
      }
    }
  },
  computed: {},
  watch: {},
  created() {
    this.loadEmployeeList()
  },
  mounted() {},
  methods: {
    // 表单子组件点击取消按钮
    Dclose() {
      this.showDialog = false
    },
    indexMethod(index) {
      return (this.pageParams.page - 1) * this.pageParams.size + index + 1
    },
    formatEmployment(id) {
      return hireType[id]
    },
    // 加载员工数据
    async loadEmployeeList() {
      try {
        const res = await getEmployeeList(this.pageParams)
        // console.log(res.data.rows)
        this.total = res.data.total
        res.data.rows.forEach(item => {
          item.timeOfEntry = item.timeOfEntry.substr(0, 10)
        })
        this.list = res.data.rows
      } catch (err) {
        console.log(err)
        this.$message.error('加载员工数据失败')
      }
    },
    // 页码改变时
    hCurrentChange(val) {
      this.pageParams.page = val
      this.loadEmployeeList()
    },
    // 每页显示数据改变时
    hSizeChange(val) {
      this.pageParams.size = val
      this.loadEmployeeList()
    },
    // 删除
    async doDel(id) {
      try {
        await delEmployee(id)
        this.$message({ type: 'success', message: '删除成功!' })
        // 动态改变页码
        if (this.list.length === 1) {
          this.pageParams.page--
          if (this.pageParams.page <= 0) {
            this.pageParams.page = 1
          }
        }
        // 重新加载
        this.loadEmployeeList()
      } catch (err) {
        this.$message.error('删除失败')
      }
    },
    // 删除按钮弹出框
    del(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.doDel(id)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 收到子组件抛出的添加成功的事件
    hUpdateEmpolyee() {
      this.showDialog = false
      // 更改页码
      this.pageParams.page = Math.ceil(++this.total / this.pageParams.size)
      // 重新渲染
      this.loadEmployeeList()
    },
    // 导出数据
    hExport() {
      import('@/vendor/Export2Excel').then(async excel => {
        // 发ajax请求，获取数据
        const res = await getEmployeeList(this.pageParams)
        const list = res.data.rows
        console.log('从后端获取的数据', list)

        const { header, data } = this.formatData(list)
        // excel表示导入的模块对象
        console.log(header, data)
        excel.export_json_to_excel({
          // header: ['姓名', '工资'], // 表头 必填
          header: header, // 表头 必填
          data: data,
          // data: [
          //   ['刘备11111111111111', 100],
          //   ['关羽', 500]
          // ], // 具体数据 必填
          filename: 'excel-list', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })
    },
    formatData(list) {
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      console.log(list)
      let header = []
      // header = ['id', 'mobile', 'username', .....]
      // data = [
      //     ['65c2', '1380000002', '管理员', ....],
      //     ['65c3', '1380000003', '孙财', ....],
      // ]
      let data = []
      // 开始代码
      // 找到一个元素
      const one = list[0]
      if (!one) {
        return { header, data }
      }
      header = Object.keys(one).map(key => {
        return map[key]
      })

      // data把list中每一个对象转成 对应的value数组
      data = list.map(obj => {
        // 把  Obj['formOfEmployment']: 1 , 2   ---> '正式'， '非正式'
        const key = obj['formOfEmployment'] // 1, 2
        obj['formOfEmployment'] = hireType[key] // hireTypEnmu:{1:'正式', '2':'非正式' }

        return Object.values(obj)
      })

      return { header, data }
    },
    // 点击分配角色按钮
    hAssignRole({ id }) {
      this.showDialogRole = true
      this.curEmployeId = id
    }
  }
}
</script>

<style scoped lang='less'>

</style>
